package oyl.selenium.config;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.springframework.util.StringUtils;
import oyl.selenium.config.translate.TranslateUtils;
import oyl.selenium.entity.Article;
import oyl.selenium.entity.Sinovinyl;
import oyl.selenium.entity.UserSettings;

import java.util.List;
import java.util.Map;

/**
 * Created by Nicky.Tang on 2021/9/18 2:06 下午
 *
 * @since 02.12.10
 */
public class MyWebDriver extends AbstractDriver {
    public static int tabIndexCur = -1;
    private boolean isFirstTry = true;
    private int tryTimes = 0;
    private final String userName;
    private final String password;
    private final String loginUrl;
    private TranslateUtils translateUtils;

    public MyWebDriver(WebDriver driver, String loginUrl, String userName, String password) {
        super(driver);
        this.loginUrl = loginUrl;
        this.userName = userName;
        this.password = password;
    }

    public void openLoginPage() {
        tabIndexCur = tabIndexCur + 1;
        try {
            if (tabIndexCur == 0) {
//                if (isFirstTry) {
//                    isFirstTry = false;
                doSync("打开登陆界面", "user_login", () -> this.driver.get(loginUrl));
//                } else {
//                    this.executorDriver.executeScript("window.location.href='" + loginUrl + "';");
//                }
            } else {
                if (isFirstTry) {
                    this.open("打开登陆界面", "user_login",
                            () -> this.executorDriver.executeScript("window.open('" + loginUrl + "')"));
                    isFirstTry = false;
                } else {
                    this.open("打开登陆界面", "user_login",
                            () -> this.executorDriver.executeScript("window.location.href='" + loginUrl + "';"));
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            if (tryTimes > 3) {
                System.out.println(">>>>>>打开登陆界面失败3次以上，放弃尝试。。。");
                throw ex;
            }
            System.out.println(">>>>>>打开登陆界面失败，继续尝试。。。");
            tabIndexCur = tabIndexCur - 1;
            tryTimes++;
            this.openLoginPage();
        }
    }

    private void loginSubmit(Sinovinyl sinovinyl) {
        WebElement elementUsername = this.driver.findElement(By.id("user_login"));
        elementUsername.sendKeys(this.userName);
        sleep(500);
        WebElement elementPassword = this.driver.findElement(By.id("user_pass"));
        elementPassword.sendKeys(this.password);
        WebElement elementSubmit = this.driver.findElement(By.id("wp-submit"));
        elementSubmit.submit();
        sleep(2500);
        this.driver.navigate().refresh();//不刷新界面，总是卡着
        this.driver.navigate().refresh();//不刷新界面，总是卡着
        this.driver.navigate().refresh();//不刷新界面，总是卡着
        doSync("执行登陆", By.xpath(".//*[@href='post-new.php']"), () -> {
        });

    }

    public void login(Sinovinyl sinovinyl) {
        openLoginPage();
        loginSubmit(sinovinyl);
    }

    private static String lowerCaseTitle(String en, String re) {
        String chepai = en.substring(en.lastIndexOf("for") + 3);
        String titlePre = en.substring(0, en.indexOf(" "));
        return re.toLowerCase().replaceAll(chepai.toLowerCase(), chepai).replaceAll(titlePre.toLowerCase(), titlePre);
    }

    private void fillArticleBody(Article articleItem, String languageCN, String suffix) {
        Map<String, String> articleItemTransalteMap = TranslateUtils.translateMap.get(articleItem.getId());
        String bodyTextStr = articleItemTransalteMap.get(articleItem.getArticlebody());
        String titleTextStr = articleItemTransalteMap.get(articleItem.getTitle());
        //if(!"阿拉伯语".equals(languageCN)){
        //     titleTextStr=lowerCaseTitle(articleItem.getTitle(), titleTextStr);
        //}
        String introduceStr = articleItemTransalteMap.get(articleItem.getIntroduce());

        // 点击写文章
        final WebElement writeMenuB = this.driver.findElement(By.xpath(".//*[@href='post-new.php']"));
        //doSync("点击写文章", By.name("post_title"), () -> writeMenuB.click());
        this.executorDriver.executeScript("arguments[0].click();", writeMenuB);
        sleep(200);
        // 文章标题
        WebElement title = this.driver.findElement(By.name("post_title"));
        title.sendKeys(titleTextStr);
        WebElement titleMeta = this.driver.findElement(By.name("_su_description"));
        titleMeta.sendKeys(titleTextStr);
        sleep(200);
        // 文章主体
        System.out.println(">>>>>>开始填充文章主体。。。");
        WebElement wenben = this.driver.findElement(By.id("content-html"));
        this.executorDriver.executeScript("arguments[0].click();", wenben);
        sleep(1500);
        WebElement articleBody = this.driver.findElement(By.id("content"));
        articleBody.sendKeys(bodyTextStr);
        sleep(1000);

        //this.driver.switchTo().frame("content_ifr");
        //this.driver.findElement(By.tagName("body")).sendKeys(bodyTextStr);
        //sleep(1500);
        //this.driver.switchTo().defaultContent();

        // 简介
        if (!StringUtils.isEmpty(articleItem.getIntroduce())) {
            WebElement introduce = this.driver.findElement(By.name("brief"));
            introduce.sendKeys(introduceStr);
        }
        // 图片链接-缩略图
        WebElement inputImageUrl = this.driver.findElement(By.className("ashu_upload_input"));
        inputImageUrl.sendKeys(articleItem.getImageurl());
        sleep(200);
        //WebElement uploadImageUrl =  this.driver.findElement(By.className("ashu_bottom"));
        //uploadImageUrl.click();
        // 图片链接-Networks
        WebElement inputNetworksImageUrlTag = this.driver.findElement(By.xpath(".//*[@href='#opengraph']"));
        this.executorDriver.executeScript("arguments[0].click();", inputNetworksImageUrlTag);
        WebElement inputNetworksImageUrl = this.driver.findElement(By.id("_su_og_image"));
        inputNetworksImageUrl.sendKeys(articleItem.getImageurl());
        sleep(200);

        // 文章标题+固定后缀
        WebElement metaDescNetworks = this.driver.findElement(By.id("_su_og_title"));
        metaDescNetworks.sendKeys(titleTextStr + " " + suffix);
        sleep(200);
        // 文章标题
        WebElement socialTitleNetworks = this.driver.findElement(By.id("_su_og_description"));
        socialTitleNetworks.sendKeys(titleTextStr);
        sleep(200);

    }

    private void writeFixedUrl(Article articleItem) {
        try {
            // 固定链接
            WebElement clickUpdateFixedUrl = this.driver.findElement(By.xpath("//button[@class='edit-slug button button-small hide-if-no-js']"));
            //clickUpdateFixedUrl.click();//直接点击会报错
            this.executorDriver.executeScript("arguments[0].click();", clickUpdateFixedUrl);
            doSync("点击编辑固定链接", "new-post-slug", () -> {
            });
            Map<String, String> articleItemTransalteMap = TranslateUtils.translateMap.get(articleItem.getId());
            String fixedUrlStr = articleItemTransalteMap.get(articleItem.getFixedurl());
            WebElement fixedUrl = this.driver.findElement(By.id("new-post-slug"));
            fixedUrl.clear();
            fixedUrl.sendKeys(fixedUrlStr);

            WebElement clickSaveFixedUrl = this.driver.findElement(By.className("save"));
            clickSaveFixedUrl.click();
        }catch (Exception ex){
            System.out.println("固定连接报错了。。。");
        }
    }

    private void fillOtherOfRight(Article articleItem) {
        // 发布日期
        String[] publishDates = articleItem.getPublishdate().split("-");
        WebElement updateDateB = this.driver.findElement(By.className("edit-timestamp"));
        this.executorDriver.executeScript("arguments[0].click();", updateDateB);
        WebElement year = this.driver.findElement(By.id("aa"));
        this.executorDriver.executeScript("arguments[0].value=" + publishDates[0], year);
        WebElement month = this.driver.findElement(By.id("mm"));
        new Select(month).selectByIndex(Integer.valueOf(publishDates[1]) - 1);
        WebElement day = this.driver.findElement(By.id("jj"));
        this.executorDriver.executeScript("arguments[0].value=" + publishDates[2], day);
        sleep(500);


        // 分类 post_category[]
        List<WebElement> classifys = this.driver.findElements(By.name("post_category[]"));
        //WebElement webElement = classifys.stream().filter(item -> item.getAttribute("value").equals(articleItem.getClassify())).findAny().orElse(null);
        WebElement webElement = classifys.get(articleItem.getClassify());
        //webElement.click();
        this.executorDriver.executeScript("arguments[0].click();", webElement);
        sleep(200);
    }

    private void writeArticleSubmit(Boolean draftBoxOnly) {
        if (Boolean.FALSE.equals(draftBoxOnly)) {
            WebElement clickPublish = this.driver.findElement(By.id("publish"));
            clickPublish.click();
        } else {
            WebElement clickBox = this.driver.findElement(By.id("save-post"));
            clickBox.click();
        }
        sleepMoment();
    }


    public void writeArticle(UserSettings userSettings, Sinovinyl sinovinyl, Article articleItem, boolean isLastArticle) {
        System.out.println(">>>>>>开始发布文章:" + articleItem.getTitle() + "。。。");
        fillArticleBody(articleItem, sinovinyl.getLanguageCN(), userSettings.getSuffix());//填充文章主体
        fillOtherOfRight(articleItem);//填充右边发布相关的信息
        writeFixedUrl(articleItem);//填充固定链接
        writeArticleSubmit(userSettings.getDraftBoxOnly());//执行发布

        if (isLastArticle) {
            String url = ((ChromeDriver) this.driver).findElementByLinkText("查看文章").getAttribute("href");
            this.executorDriver.executeScript("window.location.href='" + url + "';");
            sleep(5000);
            this.executorDriver.executeScript("document.getElementsByTagName(\"title\")[0].innerText = arguments[0]", sinovinyl.getLanguageCN());

            waitUntil(sinovinyl, By.tagName("title"));
        }
        sleepMoment();
    }

    private void waitUntil(Sinovinyl sinovinyl, By by) {
        int i = 0;
        while (i <= 5) {
            WebElement webElement = null;
            try {
                webElement = driver.findElement(by);
            } catch (NoSuchElementException ex) {
                ex.printStackTrace();
            }
            sleep(5000);
            if (webElement != null && sinovinyl.getLanguageCN().equals(webElement.getAttribute("innerText"))) {
                break;
            }
            i++;
        }
    }
}
